﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenExpressApp.MetaAttribute;
using Csla.Wpf;
using OpenExpressApp.Command;
using Csla.Core;
using System.ComponentModel;
using System.Windows;
using OpenExpressApp.Template;
using OpenExpressApp.Types;
using Csla;
using OpenExpressApp.WPF.Controls;
using System.Collections.ObjectModel;
using log4net;
using System.Collections;
using OpenExpressApp.MetaModel;
using Avalon.Windows.Controls;
using OpenExpressApp.WPF.Templete;
using OpenExpressApp.Module;
using OpenExpressApp.Module.WPF;
using System.Windows.Controls;
using Ricciolo.Controls;
using System.Reflection;
using System.Windows.Markup;
using System.Diagnostics;
using AvalonDock;
using OpenExpressApp.Module.WPF.Editors;
using Csla.OpenExpressApp;

namespace OpenExpressApp.WPF.Command
{
    //[Command("SaveToXaml", Label = "SaveToXaml", ToolTip = "SaveToXaml")]
    //public class SaveToXamlCommand : WPFListViewCommand
    //{
    //    public override void Execute(ListObjectView view)
    //    {
    //        TaskDialog.Show("Xaml", XamlWriter.Save(
    //            (view.DetailView.Control as FrameworkElement).GetFrameTemplate() as UserControl), "Xaml");
    //    }
    //}

    [Command(CommandNames.Add, ImageName = "Add.bmp", Label = "添加", ToolTip = "添加记录")]
    public class AddCommand : WPFListViewCommand
    {
        public override bool CanExecute(ListObjectView view)
        {
            bool result = false;
            var bindingList = view.Data as IBindingList;

            if (bindingList != null && bindingList.AllowNew)
            {
                bool bNavigate = true;
                var navigateView = view.NavigateQueryView;
                //如果有导航面板，则必须先给导航值赋值
                if (navigateView != null)
                {
                    foreach (var naviProperty in navigateView.NavigateProperties)
                    {
                        if (naviProperty.IsEntityId)
                        {
                            var entityProperty = naviProperty.EntityProperty;
                            object navigateObject = navigateView.CurrentObject.GetPropertyValue(entityProperty);
                            if (navigateObject == null)
                            {
                                bNavigate = false;
                                break;
                            }
                        }
                    }
                }
                result = bNavigate;
            }

            if (result)
            {
                if (view.CurrentObject != null)
                {
                    result = this.SelectedRightType(view);
                }
            }

            return result;
        }
        public override void Execute(ListObjectView view)
        {
            var currentNode = view.CurrentObject as ITreeNode;
            var list = view.Data as IBindingList;
            var treeList = list as ITreeNodeCollection;

            //是否在处理树
            bool isDealingTree = treeList != null;
            //是否已经选择了一个非根的树节点
            bool selectedChildNode = isDealingTree && currentNode != null && currentNode.ParentNode != null;

            BusinessBase newObject = null;

            #region 构造新的对象

            if (isDealingTree)
            {
                //新节点应该加在这一层节点的最后
                IList<ITreeNode> nodeOfALayer = null;

                //下面的操作会使用到关系。
                treeList.EnsureObjectRelations();

                //如果选择了一个非根的节点
                if (selectedChildNode)
                {
                    nodeOfALayer = currentNode.ParentNode.ChildrenNodes;
                }
                else
                {
                    if (treeList.Count > 0)
                    {
                        //加到最后一个根节点之后
                        nodeOfALayer = treeList.FindRoots();
                    }
                }

                if (nodeOfALayer != null && nodeOfALayer.Count > 0)
                {
                    var targetNode = nodeOfALayer[nodeOfALayer.Count - 1];
                    newObject = treeList.CreateNode(targetNode, false, false) as BusinessBase;
                }
                else
                {
                    //没有找到节点作为位置的目标，直接加到链表的最后。
                    newObject = list.AddNew() as BusinessBase;
                    //设置初始OrderNo
                    (newObject as IOrderedObject).OrderNo = 0;
                }
            }

            if (newObject == null)
            {
                newObject = list.AddNew() as BusinessBase;
            }

            #endregion

            InitProperties(newObject, view);

            #region 构造树的父子关系，刷新视图

            //如果是树形，同级新增
            if (isDealingTree)
            {
                if (selectedChildNode)
                {
                    (newObject as ITreeNode).ParentNode = currentNode.ParentNode;
                }
                //如果没有选中，或者选中的是根节点
                else
                {
                    var treeView = view.Control as MultiObjectTreeView;
                    treeView.Roots.Add(newObject);
                    //treeView.ItemsSource = view.Data as IBindingList;
                }
            }

            #endregion

            view.CurrentObject = newObject;
        }

        /// <summary>
        /// 设置某些属性
        /// 
        /// 添加记录时把导航关联值加入到当前记录中
        /// </summary>
        /// <param name="newObject"></param>
        /// <param name="view"></param>
        public static void InitProperties(BusinessBase newObject, ListObjectView view)
        {
            var navigateView = view.NavigateQueryView;
            if (navigateView != null)
            {
                navigateView.SetReferenceEntity(newObject);
            }

            //设置父对象
            var parent = view.Parent;
            if (parent != null)
            {
                //设置foreignKey
                var parentKeyProp = view.GetKeyToParentView();
                if (string.IsNullOrEmpty(parentKeyProp) == false)
                {
                    newObject.SetPropertyValue(parentKeyProp, parent.CurrentID);
                }

                //设置foreignEntity
                var parentEntityProp = view.GetKeyObjToParentView();
                if (string.IsNullOrEmpty(parentEntityProp) == false)
                {
                    newObject.SetPropertyValue(view.GetKeyObjToParentView(), parent.CurrentObject);
                }
            }
        }
    }
}